package com.yanjr.modules.sys.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yanjr.common.utils.IdGen;
import com.yanjr.modules.sys.dao.AreaDao;
import com.yanjr.modules.sys.entity.Area;
import com.yanjr.modules.sys.service.AreaService;
import com.yanjr.modules.sys.utils.UserUtils;

@Service("areaService")
@Transactional(readOnly = true)
public class AreaServiceImpl implements AreaService {

	@Autowired
	private AreaDao areaDao;
	
	@Override
	public Area get(String id) {
		return areaDao.get(id);
	}

	@Override
	public List<Area> findAll() {
		/* 从缓存取，取不到再查数据库 */
		return UserUtils.getAreaList();
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Area area) {
		String oldParentIds = area.getParentIds(); // 获取修改前的parentIds，用于更新子节点的parentIds
		Area parent = this.get(area.getParentId());
		area.setParentIds(parent.getParentIds()+parent.getId()+",");
		if(StringUtils.isEmpty(area.getId())) {
			area.setId(IdGen.uuid());
			area.setCreateBy(UserUtils.getUser().getId());
			area.setCreateDate(new Date());
			area.setUpdateBy(UserUtils.getUser().getId());
			area.setUpdateDate(new Date());
			areaDao.save(area);
		} else {
			area.setUpdateBy(UserUtils.getUser().getId());
			area.setUpdateDate(new Date());
			areaDao.update(area);
		}
		
		// 更新子节点 parentIds
		List<Area> list = areaDao.findByParentIdsLike("%,"+area.getId()+",%");
		for (Area e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, area.getParentIds()));
		}
		areaDao.update(list);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {
		areaDao.deleteById(id, "%,"+id+",%");
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}
	

}
